<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :area-type="areaType" :areas="treeAreas" v-on:handleNodeClick="onHandleNodeClick"/>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-input v-model="listQuery.device_number" class="filter-item" clearable
                      placeholder="终端编号" style="margin-left: 20px;width: 160px"></el-input>
            <el-input v-model="listQuery.number" class="filter-item" clearable
                      placeholder="水司编号" style="margin-left: 10px;width: 160px"></el-input>
            <el-input v-model="listQuery.customer_number" class="filter-item" clearable
                      placeholder="用户编号" style="margin-left: 10px;width: 160px"></el-input>
            <el-input v-model="listQuery.mobile" class="filter-item" clearable
                      placeholder="手机号" style="margin-left: 10px;width: 160px"></el-input>
            <el-input v-model="listQuery.name" class="filter-item" clearable
                      placeholder="姓名" style="margin-left: 10px;width: 160px"></el-input>
            <el-button  class="filter-item" icon="el-icon-search" style="margin-left:58px"
                        type="primary"
                        @click="getDeviceList">查询
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              ref="price-alloc"
              :loading="listLoading"
              :data="list"
              border
              highlight-current-row
              stripe
              style="width: 100%"
            >
              <el-table-column
                type="index"
                align="center"
                label="#"
                width="50">
              </el-table-column>
              <el-table-column width="100" align="center" label="姓名">
                <template v-slot="{row}">
                  <span>{{ row.customer ? row.customer.customer_name :'未知'}}</span>
                </template>
              </el-table-column>
              <el-table-column width="400" align="left" label="地址">
                <template v-slot="{row}">
                  <span>{{ row.install_address }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" width="140" label="终端号">
                <template v-slot="{row}">
                  <span>{{ row.terminal_number }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" width="140" label="水司编号">
                <template v-slot="{row}">
                  <span>{{ row.customer ? row.customer.refer_number :'未知' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" width="200" label="身份证">
                <template v-slot="{row}">
                  <span>{{ row.customer ? row.customer.identity_card:'未知' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" width="140" label="手机号">
                <template v-slot="{row}">
                  <span>{{ row.customer ?row.customer.mobile:'未知' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="余额">
                <template v-slot="{row}">
                  <span>{{ row.balance  }} </span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="信用额度">
                <template v-slot="{row}">
                  <span>{{ row.credit_limit  }} </span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="付费模式">
                <template v-slot="{row}">
                  <span>{{ row.price_rate | paymentModel}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center"  fixed="right" class-name="small-padding fixed-width" label="操作" width="280">
                <template v-slot="{row}">
                  <el-button v-if="checkPermission('缴费')" size="mini"  type="primary"
                             @click="openPaymentWindow(row)">
                    缴费
                  </el-button>
                  <el-button v-if="checkPermission('缴费')" size="mini"  type="primary"
                             @click="openRefundWindow(row)">
                    退费
                  </el-button>
                  <el-button v-if="checkPermission('缴费')"  size="mini"  type="primary"
                             @click="openRecordsWindow(row)">
                    明细
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getDeviceList"/>

            <el-dialog :title="paymentType === 1 ? '缴费':'退费'" :visible.sync="dialogFormVisible"
                       custom-class="window-small-width">
              <el-form ref="createPaymentForm" :model="form.model" :rules="form.rules" label-position="right" label-width="80px"
              >
                <el-form-item label="用户" prop="customer_id">
                  {{ form.model.customer ? form.model.customer.customer_name : ''}}
                </el-form-item>
                <el-form-item label="地址" prop="address">
                  {{ form.model.customer ?  form.model.customer.install_address : ''}}
                </el-form-item>
                <el-form-item label="终端编号" prop="terminal_number">
                  {{form.model.terminal_number}}
                </el-form-item>
                <el-form-item label="支付方式" prop="method">
                  <el-select v-model="form.model.method"   placeholder="水费计价">
                    <el-option
                      v-for="item in rechargeMethods"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="paymentType === 1" label="优惠方案" prop="discount">
                  {{ form.model.discount}}
                </el-form-item>
                <el-form-item :label=" paymentType === 1 ?'实收金额':'退款金额'" prop="real_amount">
                  <el-input type="number" v-model="form.model.real_amount"  class="filter-item"
                            placeholder="0.00"/>
                </el-form-item>
                <el-form-item v-if="paymentType === 1" label="减免" prop="additional_amount">
                  <el-input type="number" v-model="form.model.additional_amount"  class="filter-item"
                            placeholder="0.00"/>
                </el-form-item>
                <el-form-item :label="paymentType===1 ? '备注':'退费原因'" prop="remark">
                  <el-input v-model="form.model.remark" type="textarea" class="filter-item"  />
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button :loading="btnLoading" type="primary" @click=" paymentType === 1 ?createPayment():createRefund()">
                  确认
                </el-button>
              </div>
            </el-dialog>
            <el-drawer
              title="余额明细"
              size="55%"
              :visible.sync="drawer"
              direction="rtl">
              <balance-record-list :device_id="recordTargetId"></balance-record-list>
            </el-drawer>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import Pagination from '@/components/Pagination'
import {
  getDeviceList,
} from "@/api/device";
import {getAreaTree} from "@/api/area";
import {checkPermission} from "@/utils/permission"
import BalanceRecordList from "@/views/finance/balance_records.vue";
import {createBalanceRecord, createBalanceRefund} from "@/api/finance";
import moment from "moment";

const recharge_methods = [
  {
    id: 1,
    name: '现金',
  },
  {
    id: 2,
    name: '微信',
  },
  {
    id: 3,
    name: '支付宝',
  },
  {
    id: 4,
    name: '银行转账',
  },
  {
    id: 5,
    name: '其他第三方',
  }
]


export default {
  name: 'Recharge',
  components: {BalanceRecordList, Pagination,areas},
  data() {
    const validateRemark = (rule, value, callback) => {
      if(!value && this.paymentType === 2) {
        return callback(new Error('请输入退费原因'))
      }
      return callback()
    }
    return {
      dialogFormVisible: false,
      btnLoading: false,
      drawer: false,
      tableKey: 0,
      listLoading: true,
      list: [],
      areaType: 2,
      temp:{},
      paymentType:1,
      treeAreas: [],
      recordTargetId:null,
      rechargeMethods: recharge_methods,
      total: 0,
      listQuery: {
        area_code: '',
        customer_number:'',  //用户编号
        device_number: '',
        class: '',
        unit: '',
        floor: '',
        room_number: '',
        number: '',
        mobile: '',
        name: '',
        page: 1,
        pageSize: 20,
      },
      units: ['一单元', '二单元', '三单元', '四单元', '五单元', '六单元', '七单元', '八单元', '九单元', '十单元'],
      form:{
        rules:{
          real_amount: [
            { required: true, message: '请输入缴费金额', trigger: 'blur' },
            { validator: this.validateNumber, trigger: 'blur' }
          ],
          method: [
            { required: true, message: '请选择支付方式', trigger: 'change' }
          ],
          remark: [
            { validator: validateRemark, trigger: 'blur' }
          ]
        },
        model:{
          device_id:null,
          real_amount:null,
          discount:null,
          method:null,
          remark:null,
          additional_amount: 0,
          customer:null,
          terminal_number:null
        }
      }
    };
  },
  filters: {
    customerAddress(customer) {
      if(!customer) {
        return '-'
      }
      return  customer.area_name+'/'+customer.unit+'/'+customer.floor+'/'+customer.room_number
    },
    paymentModel(rate) {
      if(rate == null) {
        return '-'
      }
      return rate.payment_model === 1 ? '预付费' : '后付费'
    }
  },
  created() {
    this.getDeviceList()
    this.getAreaTree()
  },
  methods: {
    checkPermission,
    validateNumber(rule, value, callback) {
      const reg = /^-?\d+(\.\d+)?$/;
      if (value === '') {
        callback(new Error('请输入数值'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入有效的整数或小数'));
      } else {
        callback();
      }
    },
    getAreaTree() {
      getAreaTree({type: 2}).then(response => {
        this.treeAreas = response.data
      })
    },
    onHandleNodeClick: function (data) {
      if (this.listQuery.area_code !== data.code) {
        this.listQuery.area_code = data.code
        this.getDeviceList()
      }
    },
    getDeviceList() {
      this.listLoading = true
      let queryData = Object.assign({}, this.listQuery)
      queryData.device_size = queryData.device_size || 0
      getDeviceList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    openPaymentWindow(row) {
      this.paymentType = 1
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['createPaymentForm'].resetFields();
        this.form.model = Object.assign({}, {
          device_id: row.id,
          real_amount: null,
          method: null,
          remark: null,
          discount: row.discount ? row.discount.name : '未设置',
          additional_amount: 0,
          customer: row.customer,
          terminal_number: row.terminal_number
        })
      })
    },
    openRefundWindow(row){
      this.paymentType = 2
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['createPaymentForm'].resetFields();
        this.form.model = Object.assign({}, {
          device_id: row.id,
          real_amount: null,
          method: null,
          remark: null,
          customer: row.customer,
          terminal_number: row.terminal_number
        })
      })
    },
    createPayment() {
      this.$refs['createPaymentForm'].validate((valid) => {
        if (valid) {
          this.form.model.real_amount = parseFloat(this.form.model.real_amount)
          this.form.model.additional_amount = parseFloat(this.form.model.additional_amount)
          createBalanceRecord(this.form.model).then(resp => {
            if(resp.code === 20000) {
              this.dialogFormVisible = false
              this.$message.success('缴费成功')
              this.getDeviceList()
            }
          })
        }
      })
    },
    createRefund() {
      this.$refs['createPaymentForm'].validate((valid) => {
        if (valid) {
          this.form.model.real_amount = parseFloat(this.form.model.real_amount)
          this.form.model.additional_amount = parseFloat(this.form.model.additional_amount)
          createBalanceRefund(this.form.model).then(resp => {
            if(resp.code === 20000) {
              this.dialogFormVisible = false
              this.$message.success('退费成功')
              this.getDeviceList()
            }
          })
        }
      })
    },
    openRecordsWindow(row){
      this.drawer = true
      this.recordTargetId = row.id
    },
    formatDate(dateStr) {
      return moment(dateStr).format('YYYY-MM-DD')
    },
    resetQueryParams() {
      this.listQuery = {
        id: 0,
        page: 1,
        pageSize: 20,
        name: ''
      }
    }
  }
}
</script>
